<script>
import ajax from './ajax';
import UploadDragger from './upload-dragger.vue';

export default {
    inject: ['uploader'],
    components: {
        UploadDragger
    },
    props: {
        type: String,
        action: {
            type: String,
            required: true
        },
        name: {
            type: String,
            default: 'file'
        },
        data: Object,
        headers: Object,
        withCredentials: Boolean,
        multiple: Boolean,
        accept: String,
        onStart: Function,
        onProgress: Function,
        onSuccess: Function,
        onError: Function,
        beforeUpload: Function,
        drag: Boolean,
        onPreview: {
            type: Function,
            default: function() {}
        },
        onRemove: {
            type: Function,
            default: function() {}
        },
        fileList: Array,
        autoUpload: Boolean,
        listType: String,
        httpRequest: {
            type: Function,
            default: ajax
        },
        disabled: Boolean,
        limit: Number,
        onExceed: Function
    },

    data() {
        return {
            mouseover: false,
            reqs: {},

            //虚拟Id
            tempIndex: 1,
            
            //虚拟Id
            fileIndex: 1,
            // 失败的文件
            failFiles:''
        };
    },

    methods: {

        getFolderLevels(fileNames){

            var times = 0;

            var index = -1;
            for(;;){

                index = fileNames.indexOf('/', index + 1);

                if(index != -1){
                    times++;
                    continue;
                }
                break;
            }
            if(times >2){

                _this.$message({
                    showClose: true,
                    message: '您选中的文件夹最多只能包含一层子文件夹',
                    type: 'error'
                });
            }
        },

        isImage(str) {
            return str.indexOf('image') !== -1;
        },
        handleChange(ev) {
            const files = ev.target.files;

            if (!files) return;
            this.uploadFiles(files);


        },
        uploadFiles(files) {
            if (this.limit && this.fileList.length + files.length > this.limit) {
                this.onExceed && this.onExceed(files, this.fileList);
                return;
            }

            if (this.beforeUpload) {
                const before = this.beforeUpload();
                if(!before){
                    return ;
                }
            }

            let postFiles = Array.prototype.slice.call(files);
            if (!this.multiple) { postFiles = postFiles.slice(0, 1); }

            if (postFiles.length === 0) { return; }


            //构建文件夹上传对象
            var folderMap = {
                /*
                    文件夹名:  {
                       folderName: xxx,
                       fileNums:
                       totalSize: xx 
                       fileArray:[] //真实 file 对象
                       percentage: 当前上传文件 的百分比
                    }
                */
            };

            var folderMap = {};

            for (var i = 0; i < files.length; i++) {

                var folderName;

                var tmpFile = files[i];

                ////console.log(tmpFile)

                var extTmpIndex = tmpFile.name.lastIndexOf('.');
                if(extTmpIndex==-1){
                    continue;
                }
                var fileExtName = tmpFile.name.substring(extTmpIndex + 1);

                if(fileExtName.toLowerCase()!='pdf'){
                    continue;
                }
                // if(tmpFile.name=='.DS_Store'){
                //     continue;
                // }

                var webkitRelativePath = tmpFile.webkitRelativePath;

                var tmpIndex = webkitRelativePath.lastIndexOf('/');
                if (tmpIndex == -1) {
                    continue;
                }
                webkitRelativePath = webkitRelativePath.substring(0, tmpIndex);

                tmpIndex = webkitRelativePath.lastIndexOf('/');
                if (tmpIndex == -1) {
                    folderName = webkitRelativePath;
                } else {
                    folderName = webkitRelativePath.substring(tmpIndex + 1);
                }

                if (!folderName) {
                    continue;
                }
               
                if(!(/^\d{4}_.*?$/.test(folderName))){
                    this.$message({
                        showClose: true,
                        message: '文件夹名称不正确，无法与案件进行关联：' + folderName,
                        type: 'error'
                    });
                    return;
                }

                var folderObj = folderMap[folderName];

                if (!folderObj) {

                    folderObj = {
                        uid: 'folder' + this.tempIndex++,
                        folderName: folderName,
                        successNums: 0,
                        fileNums: 0,
                        totalSize: 0,
                        percentage: 0,
                        uploadingName: '',
                        status: 'init',
                        fileArray: []
                    };

                    folderMap[folderName] = folderObj;
                }
                tmpFile.uid = folderObj.uid + "_" + this.fileIndex++;
                tmpFile.md5FileName = folderName + '_' + tmpFile.name + '_' +  tmpFile.lastModifiedDate.getTime();

                folderObj.fileArray.push(tmpFile);
                folderObj.totalSize += tmpFile.size;
                folderObj.fileNums ++;

            }

            var folderArray = []
            for (var key in folderMap) {
                folderArray.push(folderMap[key]);
            }


            if(folderArray.length<=0){

                this.$message({
                    showClose: true,
                    message: '您选中的文件夹下暂无可上传的 pdf 文件',
                    type: 'error'
                });
                return;
            }

            this.onStart(folderArray);
            
        },

        uploadToServer(rawFile){
            this.$refs.input.value = null;

            return this.post(rawFile);
        },
        upload(rawFile, folderName) {

            // 校验md5，判断文件是否上传过
            var _this = this;

            _this.$ajax({

                url: '/asama/aliyun/ProofUploadRpc/check.json',
                method: 'post',
                data: {
                    md5FileName: rawFile.md5FileName,
                    securityId: _this.headers['securityId']
                },
                success: function(responseData){

                    //服务端文件不存在，才需要上传
                    if(responseData.data && responseData.data.status && responseData.data.status == 'not_exists'){

                      // 读取到的文件大小，如果是0，就报错
                      var fileSize = rawFile.size;
                      if(fileSize <= 0) {
                        if(!_this.failFiles) {
                          _this.failFiles='以下文件上传失败，请稍后重试：';
                        }
                        if(folderName != null && folderName != '' && folderName != 'undefined') {
                          _this.failFiles = _this.failFiles + ' | ' + folderName + '/' + rawFile.name;
                        } else {
                          _this.failFiles = _this.failFiles + ' | ' + rawFile.name;
                        }
                        _this.onSuccess(responseData, rawFile);
                        return;
                      }

                        //上传阿里云
                        _this.$refs.input.value = null;


                        //阿里云上传成功，通知 asama服务器 文件已经上传成功
                        // {
                        //     "accessid": "LTAIVdpNqYHVI0X8",
                        //     "policy": "eyJleHBpcmF0aW9uIjoiMjAxOC0xMi0wN1QxMzozMDoxNi44MjVaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA3Mzc0MTgyNF0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCJ1c2VyLWRpci1wcmVmaXgvIl1dfQ==",
                        //     "signature": "KzVL2a+4ERf6k0uNVst3yx78kCE=",
                        //     "dir": "user-dir-prefix/",
                        //     "host": "http://askja-oss.oss-cn-hangzhou.aliyuncs.com",
                        //     "expire": "1544189416",
                        //     "callback": "e2NhbGxiYWNrQm9keVR5cGU9YXBwbGljYXRpb24veC13d3ctZm9ybS11cmxlbmNvZGVkLCBjYWxsYmFja1VybD1odHRwOi8vODguODguODguODguOjg4ODgsIGNhbGxiYWNrQm9keT1maWxlbmFtZT0ke29iamVjdH0mc2l6ZT0ke3NpemV9Jm1pbWVUeXBlPSR7bWltZVR5cGV9JmhlaWdodD0ke2ltYWdlSW5mby5oZWlnaHR9JndpZHRoPSR7aW1hZ2VJbmZvLndpZHRofX0="
                        // }

                        var aliyunSess = responseData.data.session;

                        var postData={
                            name: rawFile.name,
                            key: aliyunSess.uploadObjectName,
                            policy: aliyunSess.policy,
                            OSSAccessKeyId: aliyunSess.accessid,
                            success_action_status: 200,
                            signature: aliyunSess.signature
                        };
                        const { uid } = rawFile;

                        var aliHost = aliyunSess.host;
                        aliHost = aliHost.substring(aliHost.indexOf("//"));

                        const options = {
                            //headers: _this.headers,
                            withCredentials: _this.withCredentials,
                            file: rawFile,
                            data: postData,
                            filename: _this.name,
                            action: aliHost,
                            onProgress: e => {
                                _this.onProgress(e, rawFile);
                            },
                            onSuccess: res => {
                                _this.$ajax({
                                    url: '/asama/aliyun/ProofUploadRpc/save.json',
                                    method: 'post',
                                    data: {

                                        md5FileName: rawFile.md5FileName,
                                        securityId: _this.headers['securityId'],

                                        fileName: rawFile.name,
                                        filePath: aliyunSess.uploadObjectName,
                                        fileSize:rawFile.size

                                    },
                                    success: function(tmpResponse){
                                        _this.onSuccess(res, rawFile);
                                        delete _this.reqs[uid];
                                    }

                                });

                            },
                            onError: err => {
                                _this.onError(err, rawFile);
                                delete _this.reqs[uid];
                            }
                        };
                        const req = _this.httpRequest(options);
                        _this.reqs[uid] = req;
                        if (req && req.then) {
                            req.then(options.onSuccess, options.onError);
                        }

                        _this.uploadToServer(rawFile);
                    }
                    //已存在，则直接触发上传成功
                    else{
                        _this.onSuccess(responseData, rawFile);
                    }

                },
                fail: function(responseData){

                    //console.log(responseData)

                    _this.$message({
                        showClose: true,
                        message: '服务异常' ,
                        type: 'error'
                    });
                    return;
                }
            });

        },
        abort(file) {
            const { reqs } = this;
            if (file) {
                let uid = file;
                if (file.uid) uid = file.uid;
                if (reqs[uid]) {
                    reqs[uid].abort();
                }
            } else {
                Object.keys(reqs).forEach((uid) => {
                    if (reqs[uid]) reqs[uid].abort();
                    delete reqs[uid];
                });
            }
        },
        post(rawFile) {
            
        },
        handleClick() {
            if (!this.disabled) {
                this.$refs.input.value = null;
                this.$refs.input.click();
            }
        },
        handleKeydown(e) {
            if (e.target !== e.currentTarget) return;
            if (e.keyCode === 13 || e.keyCode === 32) {
                this.handleClick();
            }
        }
    },

    render(h) {
        let {
            handleClick,
            drag,
            name,
            handleChange,
            multiple,
            accept,
            listType,
            uploadFiles,
            disabled,
            handleKeydown,
            failFiles
        } = this;
        const data = {
            class: {
                'el-upload': true
            },
            on: {
                click: handleClick,
                keydown: handleKeydown
            }
        };
        data.class[`el-upload--${listType}`] = true;
        return (
            <div style="text-align:left;" {...data} tabindex="0" >
        {
          drag
            ? <upload-dragger disabled={disabled} on-file={uploadFiles}>{this.$slots.default}</upload-dragger>
            : this.$slots.default
        }
        <input  class="el-upload__input" type="file" ref="input" name={name} on-change={handleChange} multiple={multiple} webkitdirectory accept={accept}></input>
        <div>
          <font style="color:red" visibility='visible'>{failFiles}</font>
        </div>
      </div>
        );
    }
};

</script>
